package com.actions;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

import com.bean.MessageCenter;
import com.bean.Suin;
import com.bean.SuinRegister;
import com.opensymphony.xwork2.ActionSupport;
import com.serviceImpl.MessageCenterServiceImpl;
import com.serviceImpl.SuinRegisterServiceImpl;
import com.serviceImpl.SuinServiceImpl;
import com.serviceImpl.UtilSupport;
import com.util.MD5Util;


public class SuinRegisterAction extends ActionSupport {

	private List<SuinRegister> listsregiter;
	private UtilSupport util;	//公用类
	private JSONArray suinRegisterJsons;
	private SuinRegisterServiceImpl suinRegisterBiz;	//供应商注册serviceimpl类
	private SuinServiceImpl suinBiz;	//供应商表sever
	private MessageCenterServiceImpl messageCenterBiz;	//供应商表sever
	
	//实体类
	private SuinRegister suinRegister;	//供应商注册类
	private Suin suin;	//供应商类

	//json
	private Boolean flag;	//判断对错
	private String msg;	//提示语
	private int offset;			//当前页
	private int pageSize=10;
	private int totalcount;		// 总记录数
	private int totalpage; 		// 总页数
	
	//查询条件

	private String realName;	//供应商名称 
	private String suinCode;	//供应商编码
	private String createTimeSt;	//起始时间
	private String createTimeEd;    //结束时间
	private Integer id;
	//接收条件
	private String captcha;	//验证码
	private String suinPass; //登录密码	
	private String suinName; //供应商登录名称
	
	public SuinServiceImpl getSuinBiz() {
		return suinBiz;
	}

	public void setSuinBiz(SuinServiceImpl suinBiz) {
		this.suinBiz = suinBiz;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public List<SuinRegister> getListsregiter() {
		return listsregiter;
	}

	public void setListsregiter(List<SuinRegister> listsregiter) {
		this.listsregiter = listsregiter;
	}

	public JSONArray getSuinRegisterJsons() {
		return suinRegisterJsons;
	}



	public void setSuinRegisterJsons(JSONArray suinRegisterJsons) {
		this.suinRegisterJsons = suinRegisterJsons;
	}



	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public String getSuinCode() {
		return suinCode;
	}

	public void setSuinCode(String suinCode) {
		this.suinCode = suinCode;
	}

	public String getCreateTimeSt() {
		return createTimeSt;
	}

	public void setCreateTimeSt(String createTimeSt) {
		this.createTimeSt = createTimeSt;
	}

	public String getCreateTimeEd() {
		return createTimeEd;
	}

	public void setCreateTimeEd(String createTimeEd) {
		this.createTimeEd = createTimeEd;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalcount() {
		return totalcount;
	}

	public void setTotalcount(int totalcount) {
		this.totalcount = totalcount;
	}

	public int getTotalpage() {
		return totalpage;
	}

	public void setTotalpage(int totalpage) {
		this.totalpage = totalpage;
	}

	//set、get
	public UtilSupport getUtil() {
		return util;
	}

	public void setUtil(UtilSupport util) {
		this.util = util;
	}

	public SuinRegisterServiceImpl getSuinRegisterBiz() {
		return suinRegisterBiz;
	}

	public void setSuinRegisterBiz(SuinRegisterServiceImpl suinRegisterBiz) {
		this.suinRegisterBiz = suinRegisterBiz;
	}

	public SuinRegister getSuinRegister() {
		return suinRegister;
	}

	public void setSuinRegister(SuinRegister suinRegister) {
		this.suinRegister = suinRegister;
	}
	
	public Boolean getFlag() {
		return flag;
	}

	public void setFlag(Boolean flag) {
		this.flag = flag;
	}

	public String getCaptcha() {
		return captcha;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public String getSuinPass() {
		return suinPass;
	}

	public void setSuinPass(String suinPass) {
		this.suinPass = suinPass;
	}

	public String getSuinName() {
		return suinName;
	}

	public void setSuinName(String suinName) {
		this.suinName = suinName;
	}

	
	public MessageCenterServiceImpl getMessageCenterBiz() {
		return messageCenterBiz;
	}

	public void setMessageCenterBiz(MessageCenterServiceImpl messageCenterBiz) {
		this.messageCenterBiz = messageCenterBiz;
	}

	/**
	 * 查找用户名是否可用
	 */
	public String findNameUsable(){
		//接收传过来的名字
		HttpServletRequest request = ServletActionContext.getRequest();
		String suinName = request.getParameter("name");
		
		flag=suinRegisterBiz.getNameUsable(suinName);
		
		return "name";
	}
	
	/**
	 * 判断验证码是否一样
	 */
	public String checkCaptcha(){
		HttpServletRequest request=ServletActionContext.getRequest();
		captcha=request.getParameter("code");
		if(captcha.equalsIgnoreCase((String)request.getSession().getAttribute("str"))){
			flag=true;
		}else{
			flag=false;
		}
		return "captcha";
	}
	
	/**
	 * 添加供应商注册
	 */
	public String addSuinRegist(){
		HttpServletRequest request=ServletActionContext.getRequest();
		
		Date date = new Date();//创建一个时间对象，获取到当前的时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置时间显示格式
		String str = sdf.format(date);// 将当前时间格式化为需要的类型
		
		//获取密码加密
		String pass = suinRegister.getSuinPass();
		String SuinPass = MD5Util.string2MD5(pass.trim());
		suinRegister.setSuinPass(SuinPass);
		
		//设置生成时间
		suinRegister.setCreateTime(Timestamp.valueOf(str));
		//设置状态（未审核）
		suinRegister.setState(0);
		//保存
		flag=suinRegisterBiz.saveSuinRegister(suinRegister);
		
		if(flag){
			msg = "您的注册申请已成功提交，审核结果稍后以短信/邮件的方式告知！ ";
		}else{
			msg = "对不起，您的注册申请提交失败！";
		}
		return "add";
	}
	
	/**
	 * 供应商登录
	 */
	public String loginCheck(){
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		
		//接收页面传过来的用户名和密码
        suinName=request.getParameter("suinName");
        suinPass=request.getParameter("suinPass");
		
		//根据用户名查找密码
        suinRegister=suinRegisterBiz.getBySuinRegister(suinName);
		
		//判断
		if(suinRegister!=null){
			String pass=suinRegister.getSuinPass();
			String userPwd=MD5Util.string2MD5(suinPass);
			//判断密码是否相同
			if(pass.equals(userPwd.trim())){
				suin=suinBiz.findSuinBySuid(suinRegister.getSuid());
				String stu=suin.getStat();
				//判断用户在suin表中的状态
				if (stu.equals("1")) {
					flag=true;
					session.setAttribute("pu", suinName);
				}else{
					flag=false;
				}
			}else{
				flag=false;
			}
		}else{
			flag=false;
		}
		return "login";
	}
	
    /**
	 * 查询显示待审核的
 	 */
	
	public String findSuinRegist(){
		HttpServletRequest request = ServletActionContext.getRequest();
		try {

			StringBuffer sqlbf=new StringBuffer("select * from audit.suin_register WHERE state=0 ");
			String	nameSql = "";
	 		String  codeSql = "";
	 		String  timeSql = "";
	 		
	 		//供应商名称
			this.realName = request.getParameter("realName");
			if(realName != null&&!realName.isEmpty()){
				realName=new String(realName.trim().getBytes("ISO-8859-1"),"UTF-8");
				nameSql=" and real_name like '%"+realName+"%'";
				sqlbf.append(nameSql);
			}
	 		//供应商编码
	 		
			this.suinCode = request.getParameter("suinCode");
			if(suinCode != null&&!suinCode.isEmpty()){
				suinCode=new String(suinCode.trim().getBytes("ISO-8859-1"),"UTF-8");
				codeSql=" and suin_code like '%"+suinCode+"%'";
				sqlbf.append(codeSql);
			}
			
			//生成时间createTimeEd; createTimeSt;
			this.createTimeSt = request.getParameter("createTimeSt");//开始时间
			
			this.createTimeEd = request.getParameter("createTimeEd");//结束时间
			
			if(createTimeSt!=null&&!createTimeSt.isEmpty()&&createTimeEd!=null&&!createTimeEd.isEmpty()){
				//格式化时间
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
				
				Date sDate = sim.parse(createTimeSt);
				Timestamp s = new Timestamp(sDate.getTime());
				
				Date eDate = sim.parse(createTimeEd);
				Timestamp e = new Timestamp(eDate.getTime());
				
				
				timeSql="and (create_time  between '"+s+"' and '"+e+"')";
				
				sqlbf.append(timeSql);
			}
			String sql =sqlbf.toString();
			
			totalcount = util.getTotalCount(sql);		//获取总条数

			totalpage = totalcount % pageSize == 0 ? totalcount / pageSize 
					: totalcount / pageSize + 1;		//获取总页数

			offset = getPageOffset();
			
			//表名
			String table="audit.suin_register";
			//主键
			String pk="id";
			//排序字段
			String sort="id";
			//当前页数
			int PageNumber=offset+1;
			
			int PageSize=pageSize;
			
			
		
			//查询条件
			String options=(sql)==null?"":"state=0"+codeSql+nameSql+timeSql;
			listsregiter=suinRegisterBiz.getAllSuinRegister(table, pk, sort, PageNumber, PageSize, options);
		
		} catch (Exception e) {
		}
		return "suinregistsuccess";
	}
	
	// Added by JSL : 获取翻页偏移量(实际上是将要翻到的页面的页索引，页索引从 0 开始)
			private int getPageOffset() {
				HttpServletRequest request=ServletActionContext.getRequest();
				String ofst = request.getParameter("offset");
				int idx = 0;
				if(ofst!=null){
					idx = Integer.valueOf(ofst);
					idx = idx < 0 ? 0 : idx;                        // 超过第一页时，不再翻页
					idx = idx >= totalpage ? (totalpage-1) : idx;	// 超过最后一页时，不再翻页		
				}
				return idx;
			}
		
			
			/**
			 * 审核供应商信息
			 * @return
			 */
			public String upSuinInfo(){
				try {
					//初始化对象
					Suin suin=new Suin();
					HttpServletRequest request = ServletActionContext.getRequest();
					int id= Integer.valueOf(request.getParameter("id"));
					suinRegister=suinRegisterBiz.findallSuinRegister(id);
					//向suin表中插入suinRegister表当前审核的数据 
					String suid = suinBiz.getNewSuid();
					suin.setSuid(suid);
					suin.setStco("01");
					//插入状态
					suin.setStat("1");
					//插入email
					suin.setEmai(suinRegister.getEmail());
					//插入地址
					suin.setPsad(suinRegister.getAddress());
					//插入电话
					suin.setPhon(suinRegister.getPhone());
					//插入供应商名称
					suin.setSuna(suinRegister.getSuinName());
					//保存
					suinBiz.saveSuin(suin);
					//执行修改
					suinRegister.setState(1);
					suinRegister.setSuid(suid);
					suinRegisterBiz.mergeSuinRegister(suinRegister);
					
					//发送邮件

					Date date = new Date();//创建一个时间对象，获取到当前的时间
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置时间显示格式
					String str = sdf.format(date);// 将当前时间格式化为需要的类型
					
					MessageCenter mc=new MessageCenter();
					mc.setTypeid(3);//发送邮件
					mc.setFlags("0001");//注册邮件
					mc.setTelno(suinRegister.getPhone());//手机号
					mc.setEmails(suinRegister.getEmail());//邮箱号
					mc.setMessage("恭喜你的申请通过审核，欢迎使用供应商管理系统！<a herf=\"#\"></a>");//发送的消息
					mc.setTimes(Timestamp.valueOf(str));
					mc.setSubject("供应商注册通知");
					//发送邮件
					messageCenterBiz.saveMessageCenter(mc);
					flag = true;
				} catch (Exception e) {
					flag = false;
				}
				return SUCCESS;
			}
	
}
